<template>
	<view>

	</view>
</template>

<script>
	export default {
		name: "send-order",
		props:{
			// forceUpdate:Boolean,
			// orderName:{
			// 	type: String,
			// 	default: '',
			// },
			// orderType:{
			// 	type: String,
			// 	default: '',
			// },
			// orderValue:{
			// 	type: String,
			// 	default: '',
			// },
			// DataList:{
			// 	type: Array,
			// 	default:[]
			// },
			
		},
		data() {
			return {
				deviceId: '',
				serviceId: '',
				writeId: '',
				notifyUuid: '',
				valueList:[],
				order:'',
				type:'',
				isJoin:false,
				isSend:false,
				ids:{
					deviceId:'',
					notifyUuid:'',
					serviceId: '',
					writeId:'',
				}
			};
		},
		watch:{
			// orderValue(v){
			// 	this.order = v
			// },
			// orderType(v){
			// 	this.type = v
			// },
			// isSend(v){
			// 	this.isSend = v
			// }
			// forceUpdate(){
			// 	this.getWatch()
			// }
		},
		methods: {
			getWatch(){
				let that = this;
				uni.$_get({
					url: "get-watch",
					that: that,
					success(res) {
						let _data = res.data;
						if(res.code == 0){
							console.log(_data,'当前手表')
							if(_data!=null){
								that.deviceId = _data.deviceId
								that.serviceId = _data.serviceId
								that.notifyUuid = _data.notifyUuid
								that.writeId = _data.writeId
								that.ids = {
									deviceId:_data.deviceId,
									notifyUuid:_data.notifyUuid,
									serviceId: _data.serviceId,
									writeId:_data.writeId,
								}
								uni.setStorageSync('isJoin',false)
								that.initBle()
							}else{
								uni.showToast({
									title:'请添加设备',
									icon:'none'
								})
							}
							// that.isJoin = true
							// that.order = 'da0b0000'
							// that.type = '0x0b'
							
							
						}
						
					},
					fail(err) {
						
					},
				});
			},
			
			initBle() {
				//关闭蓝牙模块。调用该方法将断开所有已建立的连接并释放系统资源。
				uni.closeBluetoothAdapter({
					success(res) {
						// console.log(res)
						
					}
				});
				// console.log('初始化蓝牙>>>');
				// uni.showLoading({
				// 	title: '设备连接中',
				// });
				uni.openBluetoothAdapter({
					success: (res) => { //已打开
						uni.getBluetoothAdapterState({ //蓝牙的匹配状态
							success: (res1) => {
								// console.log(res1, '“本机设备的蓝牙已打开”')
								this.createBLEConnection();
							},
							fail(error) {
								uni.showToast({
									icon: 'none',
									title: '查看手机蓝牙是否打开'
								});
							}
						});
			
					},
					fail: err => { //未打开
						uni.showToast({
							icon: 'none',
							title: '查看手机蓝牙是否打开'
						});
						uni.switchTab({
							url: '../index/index'
						})
					}
				})
			},
			//连接
			createBLEConnection() {
				// console.log(item,999)
				let that = this;
				uni.createBLEConnection({
					deviceId: that.deviceId,
					success(res) {
						that.getBLEDeviceServices();	// 获取蓝牙的服务
					},
					fail(res) {
						// uni.showToast({
						// 	title: "设备连接失败",
						// 	icon: "none",
						// });
						// uni.hideLoading()
						that.$emit('blueBack',false,that.ids)
					}
				});
			},
			//获取蓝牙的所有服务
			getBLEDeviceServices() {
				let that = this
				setTimeout(() => {
					uni.getBLEDeviceServices({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: this.deviceId,
						success: (res) => {
							// console.log("蓝牙服务", res);
							// that.serviceId = res.services[0].uuid
							//进入特征
							that.getBLEDeviceCharacteristics()
						}
					})
				}, 1500)
			},
			//获取蓝牙特征列表
			getBLEDeviceCharacteristics() {
				let that = this;
				// console.log("进入特征");
				uni.getBLEDeviceCharacteristics({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: that.deviceId,
					// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
					serviceId: that.serviceId,
					success: (res) => {
						// console.log("蓝牙特征", res);
						that.writeFn()
					},
					fail: (res) => {
						console.log(res,'失败');
						that.$emit('blueBack',false,that.ids)
						that.initBle()
						uni.hideLoading()
					}
				})
			},
			writeFn() {
				var that = this
				let order = 'ad0b0000'
				let crc = uni.$_getCrc_16_ibm('ad0b0000')
				let val = order + crc
				let ids = {
					deviceId:that.deviceId,
					notifyUuid:that.notifyUuid,
					serviceId: that.serviceId,
					writeId:that.writeId,
				}
				//指令类型
				let buff = uni.$_hexStringToArrayBuffer(val)
				uni.writeBLECharacteristicValue({
					// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
					deviceId: that.deviceId,
					// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
					serviceId: that.serviceId,
					// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
					characteristicId: that.writeId, //第二步写入的特征值
					// 这里的value是ArrayBuffer类型
					value: buff,
					success: function(res) {
						//此时设备已接收到你写入的数据
						console.log("连接写入成功", res)
						uni.setStorageSync('isJoin',true)
						that.isJoin = true
						that.startNotice()
						
						that.$emit('blueBack',that.isJoin,ids)
					},
					fail: function(err) {
						console.log(err)
						// uni.hideLoading()
						that.$emit('blueBack',false,ids)
					},
					// complete: function() {
					// 	console.log("调用结束");

					// }
				})
			},
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
			//订阅蓝牙消息返回
			startNotice() {
				var that = this;
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
					deviceId: that.deviceId,
					// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
					serviceId: that.serviceId,
					// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
					characteristicId: that.notifyUuid, //第一步 开启监听 notityid  第二步发送指令 write
					success(res) {
						//接收蓝牙返回消息
						// that.listenValueChange()
						console.log('接收蓝牙返回消息成功')
						uni.onBLECharacteristicValueChange(result => {
							// console.log("监听低功耗蓝牙设备的特征值变化", result);
							// if (result.value) {
							// 	let resHex = that.ab2hex(result.value)
							// 	console.log('设备返回原始数据', resHex)
							// 	let dataObj = that.parse_blue_response(resHex, 2)
							// 	uni.showLoading({
							// 		title: "正在获取设备数据",
							// 		mask: true,
									
							// 	});
							// 	if (dataObj.Head == '00') {
							// 		setInterval(() => {
							// 			that.writeFn()
							// 		}, 500)
							// 		// return
							// 	} else if (!dataObj.Head) {
							// 		setInterval(() => {
							// 			that.writeFn()
							// 		}, 500)
							// 	} else {
							// 		clearInterval()
							// 		that.dataToArr(dataObj.Data)
							// 	}
								
							// }
						})

					},
					fail(err) {
						console.log(err)
						that.$emit('blueBack',false,that.ids)
						// uni.hideLoading()
					}
				})
			},
			//返回的数据拆分
			dataToArr(dataList){
				this.valueList.forEach((item,index) =>{
					if(index == 0){
						item.dataLen = item.len
						item.value  = dataList.slice(0,item.dataLen)
					}else{
						item.dataLen = this.valueList[index-1].dataLen +this.valueList[index].len
						if(item.len>=2){
							let itemArr = dataList.slice(this.valueList[index-1].dataLen,item.dataLen).reverse()
							let str = itemArr.join('')
							item.value = str
							item.data = this.hex2int(str)
						}else{
							let itemArr = dataList.slice(this.valueList[index-1].dataLen,item.dataLen)
							let str = itemArr.join('')
							item.value = str
							item.data = this.hex2int(str)
							
						}
					}
				})
				// uni.showToast({
				// 	title:'获取成功！',
				// 	icon:'success'
				// })
				// uni.hideLoading()
				this.$emit('blueBack',this.valueList)
			},
			//拆分返回的数据
			parse_blue_response(str,chunkSize) {
				const regex = new RegExp('.{1,' + chunkSize + '}', 'g');
				let arr = Array.from(str.match(regex) || [])
				let dataList = []
				dataList = arr.slice(4,-2)
				let obj = {
					Head:arr[0],
					Cmd:arr[1],
					Data_len:arr[2]+ arr[3],
					Data:dataList,
					Check_Crc:arr.slice(-2),
				}
				  return obj;
			},
			// 16进制转10进制整数
			hex2int(hex) {
				var len = hex.length,
					a = new Array(len),
					code;
				for (var i = 0; i < len; i++) {
					code = hex.charCodeAt(i);
					if (48 <= code && code < 58) {
						code -= 48;
					} else {
						code = (code & 0xdf) - 65 + 10;
					}
					a[i] = code;
				}
					
				return a.reduce(function(acc, c) {
					acc = 16 * acc + c;
					return acc;
				}, 0);
			},
			// 16进制转buffer
			hexStringToArrayBuffer(str) {
				if (!str) {
					return new ArrayBuffer(0);
				}
				var buffer = new ArrayBuffer(str.length);
				let dataView = new DataView(buffer)
				let ind = 0;
				for (var i = 0, len = str.length; i < len; i += 2) {
					let code = parseInt(str.substr(i, 2), 16)
					dataView.setUint8(ind, code)
					ind++
				}
				return buffer;
			},
		},
		mounted() {
			// this.order = this.orderValue
			// this.type = this.orderType
			// this.valueList = this.DataList
			this.getWatch()
			// this.$emit('blueBack',this.isJoin)
			// this.initBle()
		}
	}
</script>

<style lang="scss">

</style>